<?php
namespace wechat;

class Wxpay
{
    public function index($total_fee,$out_trade_no)
    {
        $corpid ='wxd66ecbf25782cee9'; //企业支付分配的公众号ID
        $mch_id = '1502238151'; //商户号支付分配的ID
        $body   = '明亚商城';	//商家名称-销售商品类目
//        $total_fee = input('total_fee'); //付款金额（以分为单位）
//        $out_trade_no = input('order_card');
        if (is_numeric($total_fee))
        {
            $re = $this -> PaytoSeller($corpid,$mch_id,$body,$total_fee,$out_trade_no); //进入支付流程
            return $re;
        }
        else
        {
            echo "输入付款金额必须是数字"; //返回错误信息
        }

//        return view();
    }
    /**
     * 支付流程传递信息控制函数
     * [PaytoSeller description]
     */
    public function PaytoSeller()
    {
        $array = func_get_args();
        $corpid = $array[0];	//传入的公众号的ID
        $mch_id = $array[1];	//传入的商户号的ID
        $body   = $array[2];	//商家名称-销售商品类目
        $total_fee = $array[3]*100;	//传入的付款金额
        $nonce_str = mt_rand(100,9999);	//生成随机数
        $out_trade_no = $array[4];
     //   $out_trade_no = mt_rand(10000,999999).time().mt_rand(100,99999); //生成的订单号
        $sphill_create_ip = '47.106.164.73'; //APP和网页支付提交用户端ip
        if (empty($corpid) && empty($mch_id) && empty($total_fee))
        {

        }
        else if(empty($corpid))
        {
            echo "请输入公众号的ID";
        }
        else if (empty($mch_id))
        {
            echo "请输入商户号的ID";
        }
        else if (empty($total_fee))
        {
            echo "请输入付款金额";
        }
        else
        {
            $pay['appid'] = $corpid;
            $pay['mch_id'] = $mch_id;
            $pay['nonce_str'] = $nonce_str;
            $pay['body'] = $body;
            $pay['out_trade_no'] = $out_trade_no;
            $pay['total_fee'] = $total_fee;
            $pay['spbill_create_ip'] = $sphill_create_ip;
            $pay['trade_type']='MWEB';
            $pay['sign'] =$this->MakeSign($pay);
           // $str = 'appid='.$pay['appid'].'body='.$pay['body'].'mch_id='.$pay['mch_id'].'nonce_str='.$pay['nonce_str'].'out_trade_no='.$pay['out_trade_no'].'spbill_create_ip='.$pay['spbill_create_ip']; //生成加密的Sign
          //  $sign = md5($str);
          //  $pay['sign'] = $sign;
            $ret_xml = $this -> ToXml($pay);
            $return = $this -> curl_post_ssl($ret_xml,'');
            var_dump($return);
        }
    }
    /**
     * 生成签名
     *  @return 签名
     */
    public function MakeSign( $params ){
        //签名步骤一：按字典序排序数组参数
        ksort($params);
        $string = $this->ToUrlParams($params);
        //签名步骤二：在string后加入KEY
//        $string = $string . "&key=".$this->key;
        $string = $string . "&key=4c6749f18abaeea31dbe187f34eef2cE";
        //签名步骤三：MD5加密

        $string = strtoupper(md5($string));
        //签名步骤四：所有字符转为大写
        //   $result = strtoupper($string);
//        return json(['code' => 0, 'data' => $string1, 'msg' =>$string ]);
        return $string;

    }
    /**
     * 将参数拼接为url: key=value&key=value
     * @param   $params
     * @return  string
     */
    public function ToUrlParams( $params ){
        $string = '';
        if( !empty($params) ){
            $array = array();
            foreach( $params as $key => $value ){
                $array[] = $key.'='.$value;
            }
            $string = implode("&",$array);
        }
        return $string;
    }

    /**
     * 转换数组成XML格式
     * [ToXml description]
     * @param [type] $arr [description]
     */
    public function ToXml($arr)
    {
        $xml = "<xml>";

        if (is_array($arr))
        {
            foreach ($arr as $key => $value)
            {
                if (is_numeric($value))
                {
                    $xml .= "<".$key.">".$value."</".$key.">";
                }
                else
                {
                    $xml .= "<".$key.">"."<![CDATA[".$value."]]>"."</".$key.">";
                }
            }
            $xml .="</xml>";
            return $xml;
        }
        else
        {
            echo "这里传入的必须是一个数组";
        }
    }

    public function curl_post_ssl($value,$second)
    {
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        if (empty($second))
        {
            $second = '30';
        }
        $ch = curl_init();
        /***设置超时设置***/
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        /***设置传输设置***/
        curl_setopt($ch, CURLOPT_URL , $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
        curl_setopt($ch, CURLOPT_SSLCERT,getcwd().'/public/wxpay/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEY,getcwd().'/public/wxpay/apiclient_key.pem');
        curl_setopt($ch, CURLOPT_CAINFO, getcwd().'/public/wxpay/rootca.pem'); // CA根证书（用来验证的网站证书是否是CA颁布）
//        curl_setopt($ch, CURLOPT_SSLKEY,"/home/lizi/addons/grow/template/mobile/cash/apiclient_key.pem"); //特别注意：这里是服务器的绝对路径 且 绝对不能用变量代替！！！！！
        /***SDK要求是以POST方式上传***/
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$value);
        $data = curl_exec($ch);
        if ($data)
        {
            curl_close($ch);
            //print_r($data);
            return $data;
        }
        else
        {
            $error = curl_errno($ch); //返回链接错误的信息
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
}

